package com.cmcc.shared.widget.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.cmcc.shared.R
import com.cmcc.shared.SdkManager
import com.cmcc.shared.databinding.ActivitySharedLoginBinding
import com.cmcc.shared.utils.L
import com.cmcc.shared.utils.TokenUtils
import com.cmcc.shared.utils.showToast
import com.cmcc.shared.viewModel.SharedViewModel
import com.google.firebase.iid.FirebaseInstanceId

@Route(path = "/shared/login")
class SharedLoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivitySharedLoginBinding
    private lateinit var viewModel: SharedViewModel
    private var hasLoginInit = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = DataBindingUtil.setContentView(this, R.layout.activity_shared_login)

        viewModel = ViewModelProviders.of(this).get(SharedViewModel::class.java)

        SharedViewModel.loginToken.observe(this, Observer {
            L.d("----------Shared","token")
            if (null != it) {
                val token = it.token
                L.d("token：$token")
                TokenUtils.setUserToken(token)
//                SpHelper.setParam(this, SpKeys.USER_TOKEN, token)
            }
            finish()
        })

        userLogin()
    }

    private fun userLogin() {
        FirebaseInstanceId.getInstance().instanceId
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    val fireBaseToken = task.result?.token
                    if (fireBaseToken.isNullOrBlank()) {
                        showToast(this, getString(R.string.google_service_failed_tip))
                        finish()
                    } else {
                        val myLinkToken = SdkManager.getMyLinkToken()
                        if (myLinkToken.isNullOrBlank()) {
                            showToast(this, getString(R.string.user_info_failed_tip))
                            finish()
                        } else {
                            hasLoginInit = true
                            viewModel.userLogin(fireBaseToken, myLinkToken)
                        }
                    }
                } else {
                    L.d("getInstanceId failed", task.exception.toString())

                    showToast(this, getString(R.string.google_service_failed_tip))
                    finish()
                }
            }
    }
}